
#!/bin/bash
#author: xlp
#Version: v0.1

listforcom=$1

if [ $# -ne 1  ]
then
	echo "usage[ xstackimg.sh listcom  ]"
	exit 0
fi

echo "hello"
echo $listforcom

rm -rf reduc


mkdir reduc
cp $listforcom reduc
for fitfile in `cat $listforcom`
do
	cp $fitfile reduc
done
cd reduc
echo `pwd`


Dir_otcheck=`pwd`

rm -rf ref.fit
#Dir_data=`pwd`
rm -rf *sub.fit *lin.fit bak*.fit ker*.fit  *psf.fit
rm -rf flag.log *2sd.fit *phot.fit
rm -rf *sub.jpg 
rm -rf listcombine 


Nobj_c=3  # the min num for the object in the sub new image 
fwhm_min=1.17

rdnoise=10
gain=2

cd $Dir_otcheck
echo $Dir_otcheck
#cp -r ~/software/xsoft/newxgwacmatchsoft/* $Dir_otcheck

xdefineDir ( )
{
stringtimeForMonitorT=`date -u +%Y%m%d`
Dir_monitor_allplot=`echo $Dir_otcheck"/"$stringtimeForMonitorT`
if test ! -r $Dir_monitor_allplot 
then
    mkdir $Dir_monitor_allplot
fi
fitscutpngmonitor=`echo $Dir_monitor_allplot"/otcheck_"$stringtimeForMonitorT".1.log"`
OTCandidateslist=`echo $Dir_monitor_allplot"/OTCandidateslist.1.log"`

if test ! -r $HOME/iraf
then
    echo "no iraf1 file with the name of iraf1"
    exit        
fi
}


xmatchTwoImage (  )
{
	echo "xmatchTwoImage" >>$fitscutpngmonitor
    echo "xmatchTwoImage"
    #matchflag=tolerance
    matchflag=triangles
    fitorder=2
    toleranceradius=20
    xNpixel=`gethead $NewOTimage "NAXIS1" | awk '{print($1)}' `
    yNpixel=`gethead $NewOTimage "NAXIS1" | awk '{print($1)}'`
    echo $xNpixel $yNpixel
    echo "fit order is: $fitorder"
    
    echo `date` "First tolerance match"
    if test -r $NewOTimage
	then
	echo "have  $NewOTimage "
	else
	echo "no $NewOTimage" 
	fi
     rm -rf $tran2
  
	echo "======xyxymatch==="
  cd $HOME/iraf
    cp -f login.cl.old login.cl
    echo noao >> login.cl
    echo image >> login.cl
    echo immatch >> login.cl
    echo "cd $Dir_otcheck" >> login.cl
   echo "geomap(\"$imagetmp1sd\", \"$imagetrans1sd\", transfo=\"$inprefix\", verbos-, xmin=1, xmax=$xNpixel, ymin=1, ymax=$yNpixel,         fitgeom=\"general\", functio=\"legendre\",xxorder=$fitorder,xyorder=$fitorder,xxterms=\"half\",yxorder=$fitorder,yyorder=$fitorder,          yxterms=\"half\", maxiter=2,reject=2.5,inter-)" >>login.cl
    echo "geotran(\"$rawOTimage\", \"$tran2\", \"$imagetrans1sd\", \"$inprefix\", interpolant=\"spline3\")" >>login.cl
    echo logout >> login.cl
    #cl < login.cl
    cl < login.cl >xlogfile
    cd $HOME/iraf
    cp -f login.cl.old login.cl
    cd $Dir_otcheck
	echo  "xyxymatch and geomap are over"
    if test -r $tran2
    then
    	echo  $tran2 >>listcombine
    else
	echo "No $tran2"
    fi
    	echo "@@@@@@@@@@"

}

xcombine ( )
{

    echo "xcombine"
    cat listcombine
cd $HOME/iraf
cp -f login.cl.old login.cl
echo noao >> login.cl
echo digiphot >> login.cl
echo daophot >>login.cl
echo "cd $Dir_otcheck" >> login.cl
echo flpr >> login.cl
echo "imcombine(\"@listcombine\",\"$comimage\", reject=\"crreject\",combine=\"median\",scale=\"exposure\",weight=\"exposure\",rdnoise=$rdnoise,gain=$gain)" >>login.cl
echo logout >>login.cl
cl < login.cl >xlogfile
#cl < login.cl
#----------------------------------------------
cd $Dir_otcheck
newwcsfitnew=`echo $comimage | sed 's/.fit/.new/g'`
nnewwcsfitnew=`echo $comimage | sed 's/.fit/_wcs.fit/g'`
~/software/softgft_mainFocus/xastro_cgft.sh $comimage
wait
ls $comimage $nnewwcsfitnew
echo "============"
echo "To correct the real exptime for the stacked image"
Ncombine=`cat listcombine | wc -l | awk '{print($1)}'`
Nexptime=0
cat listcombine | while read lineexp
do
	echo $lineexp
	exptime=`gethead $lineexp "exptime"`
	Nexptime1=`echo $Nexptime $exptime | awk '{print($1+$2)}'`
	Nexptime=`echo $Nexptime1 | awk '{print($1)}'`
done
xsethead
rm -rf listcombine listcom listcom_as
mv $comimage $nnewwcsfitnew ../
cd ../
#rm -rf reduc
echo $nnewwcsfitnew >newcomimage.log
echo "==========="
echo "over"
}

xsethead ( )
{
	echo "=====xsethead====="
	#Nexptime   Ncombine	
	sethead -kr X Nexptime="\'$Nexptime ' " Ncombine="\'$Ncombine' "  $comimage

}

xotcheckdefine (  )
{
    inprefix=`echo $NewOTimage | sed 's/.fit//g'`
    inprefixfit=`echo $inprefix | awk '{print($1"*.fit")}'`
    inprefixallfile=`echo $inprefix | awk '{print($1"*")}'`
    #inprefixallfile=`echo $NewOTimage | sed 's/.fit/*/'`
    NewOTimagebg=`echo $NewOTimage | sed 's/.fit/_bg.fit/'`
    NewOTimagesubbg=`echo $NewOTimage | sed 's/.fit/_subbg.fit/'`
    photometry_comp=`echo $NewOTimage | sed 's/.fit/_phot.fit/'`
    photometry_compStarList=`echo $NewOTimage | sed 's/.fit/_phot.cat/'`
    refimagebg=`echo $refimage | sed 's/.fit/_bg.fit/'`
    refimagesubbg=`echo $refimage | sed 's/.fit/_subbg.fit/'`
    #refimageStarList_fwhm=`echo $refimage | sed 's/.fit/_fwhm.cat/'`
    NewOTimageStarList_fwhm=`echo $NewOTimage | sed 's/.fit/_fwhm.cat/'` 
    NewOTimageStarList_xy=`echo $NewOTimage | sed 's/.fit/.xy/'`
    NewOTimage_1=`echo $NewOTimage | awk '{print($1"[1]")}'`
    NewOTimageStarList=`echo $NewOTimage | sed 's/.fit/.cat/'`
    #Newimageimstat=`echo $NewOTimage_1 | awk '{print($1"[40:60,40:60]")}'`
    Newimageimstat=`echo $NewOTimage | awk '{print($1"[40:60,40:60]")}'`

    resfile=`echo $inprefix | awk '{print($1".imstat")}'`
    imagetmp1sd=`echo $NewOTimage | sed 's/.fit/.mattmp1sd/'`
    imagetrans1sd=`echo $NewOTimage | sed 's/.fit/.trans1sd/'`
    tran2=`echo $NewOTimage | sed 's/.fit/_2sd.fit/'`
    fluxcorr=`echo $NewOTimage | sed 's/.fit/_fluxcorr.fit/'`
    #inprefix=`echo $NewOTimage | sed 's/.fit//'`
    subimage=`echo $NewOTimage | sed 's/.fit/_sub.fit/'`
    subimageStarList=`echo $NewOTimage | sed 's/.fit/_sub.cat/'`
    ccdimgjpg=`echo $subimage | sed 's/\.fit/\.jpg/'`
    psfmatchimage=`echo $NewOTimage | sed 's/.fit/_psfmatch.fit/'`
    linmatchimage=`echo $NewOTimage | sed 's/.fit/_linmatch.fit/'`
    OTconfirmlst=`echo $NewOTimage | sed  's/.fit/_otconfirmlst.cat/'`
    OTconfirmlstnew=`echo $NewOTimage | sed  's/.fit/_otconfirmlst_new.cat/'`
    OTconfirmlstTmp=`echo $NewOTimage | sed  's/.fit/_otconfirmlst_tmp.cat/'`
    OTconfirmlstRef=`echo $NewOTimage | sed  's/.fit/_otconfirmlst_ref.cat/'`
    OTconfirmlstRef_crosstalk=`echo $NewOTimage | sed  's/.fit/_otconfirmlst_ref_crosstalk.cat/'`
    
    OTconfirmlstPsf=`echo $NewOTimage | sed  's/.fit/_otconfirmlst_psf.cat/'`
    rawOTimage=`echo $NewOTimage | sed 's/_wcs.fit/.fit/g'`
    
}


xmkmovie ( )
{
    gifname=subfitmovie.gif
    convert -delay 10 *sub.jpg -loop 0 $gifname
}



xfit2jpg ( )
{
    xim=50
    yim=50
    subridus=50

    if test -r $subimage
    then
        jpgimg=`echo $subimage | sed 's/\.fit/.jpg/g'`
        python fits_cut_to_png_galaxy.py $subimage $jpgimg $xim $yim $subridus \" \"
    fi

}

xcheckrefimage_new ( )
{

echo "=======check the ref.fit =========="

if test -r ref.fit
    then
        echo "OK"
    else
        echo "no ref.fit"
	if test ! -s listcom_as
	then
		echo "no image with wcs"
		break
	fi
        newlastimage=`head -1 listcom_as | awk '{print($1)}'`
        refimage=`echo $newlastimage | sed 's/.fit/_ref.fit/g'`
        
        cp $newlastimage $refimage 


        refimageStarList=`echo $refimage | sed 's/.fit/.cat/g'`
        refimageStarList_fwhm=`echo $refimage | sed 's/.fit/.fwhm/g'`
        comimage=`echo $newlastimage | sed 's/.fit/_c.fit/g'`
        cp $refimage ref.fit
        echo $refimage
	cp ~/software/softgft_mainFocus/* ./
        sex $refimage -c daofind.sex -DETECT_THRESH 5 -ANALYSIS_THRESH 5
        mv image.sex $refimageStarList
        head -1 $refimageStarList 
        echo $refimageStarList
        echo $refimage
     #   cat $refimageStarList | awk '{if($4==0)print($0)}' | sort -n -k 8 | head -4  >$refimageStarList_fwhm
        cat $refimageStarList | awk '{if($8==0)print($0)}' | sort -n -k 4 | awk '{print($1,$2)}' >ref.xy
	echo "=======ref.xy========="
        cat ref.xy
        xy2sky -d $newlastimage @ref.xy  | awk '{print($1,$2)}'>ref.radec
        cat ref.radec
        echo "============="
    fi
}

xcheckNewimage_new ( )
{
for NewOTimage in `cat listcom_as`
do
    echo $NewOTimage 
    xotcheckdefine
    cp ~/software/softgft_mainFocus/* ./
    echo $NewOTimage
    rm -rf image.sex
    sex $NewOTimage -c daofind.sex -DETECT_THRESH 5 -ANALYSIS_THRESH 5
    echo "get source list from $NewOTimage, over"
    head -1 image.sex
    mv image.sex $NewOTimageStarList 
    head -1 $NewOTimageStarList
    sky2xy $NewOTimage @ref.radec | awk '{print($5,$6)}'>$NewOTimageStarList_xy
    echo "$NewOTimageStarList_xy"
    head -1 $NewOTimageStarList_xy
    #cat $NewOTimageStarList_xy
    echo "&&&&&&&"
    echo "$imagetmp1sd"
    wc ref.xy
    wc $NewOTimageStarList_xy
    paste ref.xy $NewOTimageStarList_xy | awk '{print($1,$2,$3,$4," 1   1   ")}' | grep -v "-">$imagetmp1sd 
    head -5 $imagetmp1sd 
    echo "========$imagetmp1sd=========="
    xmatchTwoImage
    echo "For $NewOTimage, the process is over"
    echo "============"
done
}


xastronomy ( )
{
    echo "xastronomy"
    rm -rf listcom_as
    for fitfileas in `cat $listforcom`
    do
        echo $fitfileas
	gethead $fitfileas "CRVAL1" >crval1.log
	if test  -s crval1.log
	then
		echo "Astronomy is finished"
		ls $fitfileas >>listcom_as
	else
        	newfitfileas=`echo $fitfileas | sed 's/.fit/.new/g'`
        	nnewfitfileas=`echo $fitfileas | sed 's/.fit/_wcs.fit/g'`
       		#objra=`gethead $fitfileas "objctra" | awk '{print($1)}'`
       		#objctdec=`gethead $fitfileas "objctdec" | awk '{print($1)}'`
       		#solve-field -O  -p --use-sextractor -scale -H 0.6 -L 0.5 -u app -3 $objra -4 $objctdec -5 1  $fitfileas
		~/software/softgft_mainFocus/xastro_cgft.sh $fitfileas
       		wait
       		if test -r $nnewfitfileas
       		then
       		    echo "$fitfileas astronomy calibrated to $nnewfitfileas "
       		    #cp $newfitfileas $fitfileas 
       		    ls $nnewfitfileas >>listcom_as
       		fi
	fi

    done

}


#while : 
#do
echo "test"
xotcheckdefine
    xastronomy
    xdefineDir
    xcheckrefimage_new
    xcheckNewimage_new
    xcombine
#done


